import express from 'express';
import { randomUUID } from 'node:crypto';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import cors from 'cors';

// Create a wrapper database connection function to handle environment variables
function createDatabaseConnection() {
  // For MCP server, use a simple in-memory SQLite database or fallback
  // since environment variables might not be available in standalone mode
  const { drizzle } = require('drizzle-orm/sqlite-proxy');
  const { sqliteTable, integer, text, real } = require('drizzle-orm');
  
  // Mock schema for MCP server (simplified version)
  const customers = sqliteTable('customers', {
    id: integer('id').primaryKey(),
    name: text('name'),
    email: text('email'),
    phone: text('phone'),
    address: text('address'),
    createdAt: integer('created_at')
  });

  const products = sqliteTable('products', {
    id: integer('id').primaryKey(),
    name: text('name'),
    description: text('description'),
    price: real('price'),
    category: text('category'),
    sku: text('sku'),
    createdAt: integer('created_at')
  });

  const orders = sqliteTable('orders', {
    id: integer('id').primaryKey(),
    customerId: integer('customer_id'),
    totalAmount: real('total_amount'),
    status: text('status'),
    cancelReason: text('cancel_reason'),
    createdAt: integer('created_at'),
    updatedAt: integer('updated_at')
  });

  const orderItems = sqliteTable('order_items', {
    id: integer('id').primaryKey(),
    orderId: integer('order_id'),
    productId: integer('product_id'),
    price: real('price'),
    quantity: integer('quantity'),
    subtotal: real('subtotal')
  });

  const inventory = sqliteTable('inventory', {
    id: integer('id').primaryKey(),
    productId: integer('product_id'),
    quantity: integer('quantity'),
    lowStockThreshold: integer('low_stock_threshold')
  });

  const orderActivities = sqliteTable('order_activities', {
    id: integer('id').primaryKey(),
    orderId: integer('order_id'),
    action: text('action'),
    fromStatus: text('from_status'),
    toStatus: text('to_status'),
    description: text('description'),
    performedBy: text('performed_by'),
    createdAt: integer('created_at')
  });

  const schema = {
    customers,
    products,
    orders,
    orderItems,
    inventory,
    orderActivities
  };

  return { db: drizzle(async (sql, params) => {
    // Mock database operations for MCP server
    console.log('Mock DB operation:', sql, params);
    return [];
  }, { schema }), schema };
}

// Create MCP server
export function createMcpServer() {
  const server = new McpServer({
    name: 'seller-management-api',
    version: '1.0.0',
    description: 'MCP server for seller management system API'
  });

  // Helper function to get status text
  function getStatusText(status: string): string {
    const statusMap: Record<string, string> = {
      'pending': '待支付',
      'paid': '已支付',
      'shipped': '已发货',
      'delivered': '已交付',
      'cancelled': '已取消'
    };
    return statusMap[status] || status;
  }

  // Order Management Tools

  server.registerTool(
    'get-order',
    {
      title: '获取订单详情',
      description: '根据订单ID获取订单详细信息，包括商品明细和活动记录',
      inputSchema: {
        orderId: z.number().describe('订单ID')
      }
    },
    async ({ orderId }) => {
      try {
        // Mock order database with different data for different order IDs
        const orderDatabase: Record<number, any> = {
          1001: {
            customerName: '张三',
            customerEmail: 'zhangsan@example.com',
            totalAmount: 299.99,
            status: 'paid',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 3,
            updatedAt: Math.floor(Date.now() / 1000) - 43200,
            items: [
              { productName: '智能手机', quantity: 1, price: 299.99, subtotal: 299.99 }
            ],
            activities: [
              { description: '订单创建', createdAt: Math.floor(Date.now() / 1000) - 86400 * 3 },
              { description: '订单支付完成', createdAt: Math.floor(Date.now() / 1000) - 86400 * 2 }
            ]
          },
          1002: {
            customerName: '李四',
            customerEmail: 'lisi@example.com',
            totalAmount: 899.97,
            status: 'shipped',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 5,
            updatedAt: Math.floor(Date.now() / 1000) - 21600,
            items: [
              { productName: '笔记本电脑', quantity: 1, price: 599.99, subtotal: 599.99 },
              { productName: '鼠标', quantity: 2, price: 149.99, subtotal: 299.98 }
            ],
            activities: [
              { description: '订单创建', createdAt: Math.floor(Date.now() / 1000) - 86400 * 5 },
              { description: '订单支付完成', createdAt: Math.floor(Date.now() / 1000) - 86400 * 4 },
              { description: '订单已发货', createdAt: Math.floor(Date.now() / 1000) - 86400 * 1 }
            ]
          },
          1003: {
            customerName: '王五',
            customerEmail: 'wangwu@example.com',
            totalAmount: 199.99,
            status: 'pending',
            createdAt: Math.floor(Date.now() / 1000) - 43200,
            updatedAt: Math.floor(Date.now() / 1000) - 3600,
            items: [
              { productName: '耳机', quantity: 1, price: 199.99, subtotal: 199.99 }
            ],
            activities: [
              { description: '订单创建', createdAt: Math.floor(Date.now() / 1000) - 43200 }
            ]
          },
          2001: {
            customerName: '企业客户A',
            customerEmail: 'enterprise@example.com',
            totalAmount: 2499.95,
            status: 'delivered',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 10,
            updatedAt: Math.floor(Date.now() / 1000) - 86400 * 2,
            items: [
              { productName: '办公电脑', quantity: 5, price: 499.99, subtotal: 2499.95 }
            ],
            activities: [
              { description: '订单创建', createdAt: Math.floor(Date.now() / 1000) - 86400 * 10 },
              { description: '订单支付完成', createdAt: Math.floor(Date.now() / 1000) - 86400 * 9 },
              { description: '订单已发货', createdAt: Math.floor(Date.now() / 1000) - 86400 * 7 },
              { description: '订单已交付', createdAt: Math.floor(Date.now() / 1000) - 86400 * 2 }
            ]
          }
        };

        // Get order data or use default if ID not found
        const orderData = orderDatabase[orderId] || {
          customerName: `客户${orderId}`,
          customerEmail: `customer${orderId}@example.com`,
          totalAmount: 99.99 + (orderId % 100),
          status: ['pending', 'paid', 'shipped', 'delivered'][orderId % 4],
          createdAt: Math.floor(Date.now() / 1000) - 86400 * (orderId % 10 + 1),
          updatedAt: Math.floor(Date.now() / 1000) - 3600 * (orderId % 24),
          items: [
            { productName: `产品${orderId}`, quantity: orderId % 5 + 1, price: 49.99 + (orderId % 50), subtotal: (49.99 + (orderId % 50)) * (orderId % 5 + 1) }
          ],
          activities: [
            { description: '订单创建', createdAt: Math.floor(Date.now() / 1000) - 86400 * (orderId % 10 + 1) }
          ]
        };

        const orderText = `订单 #${orderId}
客户: ${orderData.customerName} (${orderData.customerEmail})
状态: ${getStatusText(orderData.status)}
总金额: ¥${orderData.totalAmount.toFixed(2)}
创建时间: ${new Date(orderData.createdAt * 1000).toLocaleString('zh-CN')}
更新时间: ${new Date(orderData.updatedAt * 1000).toLocaleString('zh-CN')}`;

        const itemsText = orderData.items.map(item => 
          `- ${item.productName}: ${item.quantity} × ¥${item.price.toFixed(2)} = ¥${item.subtotal.toFixed(2)}`
        ).join('\n');

        const activitiesText = orderData.activities.map(activity => 
          `[${new Date(activity.createdAt * 1000).toLocaleString('zh-CN')}] ${activity.description}`
        ).join('\n');

        const result = `${orderText}\n\n商品明细:\n${itemsText}\n\n活动记录:\n${activitiesText}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `获取订单详情失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  server.registerTool(
    'list-orders',
    {
      title: '订单列表查询',
      description: '根据条件查询订单列表，支持状态、日期范围、客户名称等筛选',
      inputSchema: {
        status: z.string().optional().describe('订单状态: pending, paid, shipped, delivered, cancelled'),
        startDate: z.string().optional().describe('开始日期 (YYYY-MM-DD)'),
        endDate: z.string().optional().describe('结束日期 (YYYY-MM-DD)'),
        customerName: z.string().optional().describe('客户名称'),
        limit: z.number().optional().default(5).describe('返回数量限制')
      }
    },
    async ({ status, startDate, endDate, customerName, limit }) => {
      try {
        // Mock orders data
        const mockOrders = [
          { id: 1001, customerName: '张三', totalAmount: 299.99, status: 'paid', createdAt: Math.floor(Date.now() / 1000) - 86400 },
          { id: 1002, customerName: '李四', totalAmount: 599.99, status: 'shipped', createdAt: Math.floor(Date.now() / 1000) - 172800 },
          { id: 1003, customerName: '王五', totalAmount: 199.99, status: 'pending', createdAt: Math.floor(Date.now() / 1000) - 43200 }
        ];

        // Filter mock data based on parameters
        let filteredOrders = mockOrders;
        
        if (status) {
          filteredOrders = filteredOrders.filter(order => order.status === status);
        }
        
        if (customerName) {
          filteredOrders = filteredOrders.filter(order => 
            order.customerName.includes(customerName)
          );
        }

        if (limit) {
          filteredOrders = filteredOrders.slice(0, limit);
        }

        const ordersText = filteredOrders.map(order => 
          `#${order.id} | ${getStatusText(order.status)} | ¥${order.totalAmount} | ${order.customerName} | ${new Date(order.createdAt * 1000).toLocaleDateString('zh-CN')}`
        ).join('\n');

        const result = `找到 ${filteredOrders.length} 个订单\n\n${ordersText || '未找到符合条件的订单'}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `查询订单列表失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  // Customer Management Tools

  server.registerTool(
    'get-customer',
    {
      title: '获取客户信息',
      description: '根据客户ID获取客户详细信息',
      inputSchema: {
        customerId: z.number().describe('客户ID')
      }
    },
    async ({ customerId }) => {
      try {
        // Mock customer database with different data for different IDs
        const customerDatabase: Record<number, any> = {
          1: {
            name: '张三',
            email: 'zhangsan@example.com',
            phone: '13800138001',
            address: '北京市朝阳区建国路123号',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 30
          },
          2: {
            name: '李四',
            email: 'lisi@example.com',
            phone: '13800138002',
            address: '上海市浦东新区陆家嘴456号',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 45
          },
          3: {
            name: '王五',
            email: 'wangwu@example.com',
            phone: '13800138003',
            address: '广州市天河区体育西路789号',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 15
          },
          1001: {
            name: '企业客户A',
            email: 'enterprise@example.com',
            phone: '400-123-4567',
            address: '深圳市南山区科技园101号',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 90
          },
          2001: {
            name: 'VIP客户B',
            email: 'vip@example.com',
            phone: '13888888888',
            address: '杭州市西湖区文三路202号',
            createdAt: Math.floor(Date.now() / 1000) - 86400 * 120
          }
        };

        // Get customer data or use default if ID not found
        const customerData = customerDatabase[customerId] || {
          name: `客户${customerId}`,
          email: `customer${customerId}@example.com`,
          phone: '13800138000',
          address: '未知地址',
          createdAt: Math.floor(Date.now() / 1000) - 86400 * 7
        };

        const result = `客户 #${customerId}
姓名: ${customerData.name}
邮箱: ${customerData.email}
电话: ${customerData.phone}
地址: ${customerData.address}
创建时间: ${new Date(customerData.createdAt * 1000).toLocaleString('zh-CN')}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `获取客户信息失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  // Product Management Tools

  server.registerTool(
    'get-product',
    {
      title: '获取产品信息',
      description: '根据产品ID获取产品详细信息',
      inputSchema: {
        productId: z.number().describe('产品ID')
      }
    },
    async ({ productId }) => {
      try {
        // Mock product database with different data for different product IDs
        const productDatabase: Record<number, any> = {
          1: {
            name: '智能手机',
            description: '高性能智能手机，6.7英寸屏幕，8GB内存，256GB存储',
            price: 2999.99,
            category: '电子产品',
            sku: 'PHONE-001',
            quantity: 25,
            lowStockThreshold: 5
          },
          2: {
            name: '笔记本电脑',
            description: '轻薄便携笔记本电脑，15.6英寸屏幕，16GB内存，512GB SSD',
            price: 5999.99,
            category: '电子产品',
            sku: 'LAPTOP-001',
            quantity: 12,
            lowStockThreshold: 3
          },
          3: {
            name: '无线耳机',
            description: '蓝牙5.0无线耳机，主动降噪，30小时续航',
            price: 299.99,
            category: '音频设备',
            sku: 'AUDIO-001',
            quantity: 48,
            lowStockThreshold: 10
          },
          4: {
            name: '智能手表',
            description: '健康监测智能手表，心率检测，GPS定位',
            price: 899.99,
            category: '穿戴设备',
            sku: 'WEARABLE-001',
            quantity: 7,
            lowStockThreshold: 5
          },
          5: {
            name: '游戏鼠标',
            description: '电竞游戏鼠标，16000 DPI，RGB灯光',
            price: 199.99,
            category: '电脑配件',
            sku: 'ACCESSORY-001',
            quantity: 35,
            lowStockThreshold: 8
          }
        };

        // Get product data or use default if ID not found
        const productData = productDatabase[productId] || {
          name: `产品${productId}`,
          description: `这是产品${productId}的描述`, 
          price: 99.99 + (productId % 100),
          category: ['电子产品', '家居用品', '服装', '图书'][productId % 4],
          sku: `SKU-${productId.toString().padStart(4, '0')}`,
          quantity: productId % 50,
          lowStockThreshold: 10
        };

        let status = '正常';
        if (productData.quantity === 0) {
          status = '缺货';
        } else if (productData.quantity <= productData.lowStockThreshold) {
          status = '低库存';
        }

        const result = `产品 #${productId}
名称: ${productData.name}
描述: ${productData.description}
价格: ¥${productData.price.toFixed(2)}
分类: ${productData.category}
SKU: ${productData.sku}
库存: ${productData.quantity} 件
低库存阈值: ${productData.lowStockThreshold} 件
状态: ${status}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `获取产品信息失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  // Inventory Management Tools

  server.registerTool(
    'check-inventory',
    {
      title: '检查库存',
      description: '检查产品库存状态，包括低库存预警',
      inputSchema: {
        productId: z.number().describe('产品ID')
      }
    },
    async ({ productId }) => {
      try {
        // Mock inventory data
        const inventoryInfo = {
          productId: productId,
          productName: '示例产品',
          quantity: 5,
          lowStockThreshold: 10
        };

        let status = '正常';
        if (inventoryInfo.quantity === 0) {
          status = '缺货';
        } else if (inventoryInfo.quantity <= inventoryInfo.lowStockThreshold) {
          status = '低库存';
        }

        const result = `产品: ${inventoryInfo.productName} (#${inventoryInfo.productId})
当前库存: ${inventoryInfo.quantity} 件
低库存阈值: ${inventoryInfo.lowStockThreshold} 件
状态: ${status}`;

        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `检查库存失败: ${error.message}` }],
          isError: true
        };
      }
    }
  );

  // Dashboard Resources

  server.registerResource(
    'dashboard-stats',
    'dashboard://stats',
    {
      title: '仪表盘统计数据',
      description: '系统仪表盘的关键统计数据',
      mimeType: 'application/json'
    },
    async (uri) => {
      try {
        // Mock dashboard stats
        const stats = {
          totalOrders: 156,
          totalRevenue: 45987.65,
          totalCustomers: 89,
          totalProducts: 45,
          pendingOrders: 12,
          lowStockProducts: 3,
          updatedAt: new Date().toISOString()
        };

        return {
          contents: [{
            uri: uri.href,
            text: JSON.stringify(stats, null, 2)
          }]
        };
      } catch (error: any) {
        return {
          contents: [{
            uri: uri.href,
            text: JSON.stringify({ error: `获取统计数据失败: ${error.message}` }, null, 2)
          }]
        };
      }
    }
  );

  return server;
}

// Create and configure Express app for Streamable HTTP transport
export function createApp() {
  const app = express();
  app.use(express.json());

  // Enable CORS for browser clients
  app.use(cors({
    origin: '*',
    exposedHeaders: ['Mcp-Session-Id'],
    allowedHeaders: ['Content-Type', 'mcp-session-id']
  }));

  // Map to store transports by session ID
  const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};

  // MCP POST endpoint
  app.post('/mcp', async (req, res) => {
    // Debug: log all headers to see what MCP Inspector sends
    console.log('Received MCP request headers:', req.headers);
    console.log('Request body method:', req.body?.method);
    
    // Check for session ID in different header formats
    let sessionId = req.headers['mcp-session-id'] as string | undefined;
    if (!sessionId) {
      sessionId = req.headers['mcp-session-id'] as string | undefined; // lowercase
    }
    if (!sessionId) {
      sessionId = req.headers['mcp_session_id'] as string | undefined; // underscore
    }
    
    console.log('Session ID found:', sessionId);
    
    try {
      let transport: StreamableHTTPServerTransport;
      if (sessionId && transports[sessionId]) {
        // Reuse existing transport
        console.log('Reusing existing transport for session:', sessionId);
        transport = transports[sessionId];
      } else if (!sessionId && req.body && isInitializeRequest(req.body)) {
        // New initialization request
        console.log('New initialization request received');
        transport = new StreamableHTTPServerTransport({
          sessionIdGenerator: () => randomUUID(),
          onsessioninitialized: (newSessionId) => {
            // Store the transport by session ID
            console.log('Session initialized with ID:', newSessionId);
            transports[newSessionId] = transport;
          }
        });

        // Clean up transport when closed
        transport.onclose = () => {
          if (transport.sessionId) {
            console.log('Transport closed for session:', transport.sessionId);
            delete transports[transport.sessionId];
          }
        };

        // Create and connect MCP server
        const server = createMcpServer();
        await server.connect(transport);

        await transport.handleRequest(req, res, req.body);
        return;
      } else if (sessionId && !transports[sessionId]) {
        // Session ID provided but no transport found
        console.log('Session ID provided but no transport found:', sessionId);
        res.status(400).json({
          jsonrpc: '2.0',
          error: {
            code: -32000,
            message: 'Invalid session ID',
          },
          id: null,
        });
        return;
      } else {
        // Invalid request - no session ID and not initialization
        console.log('Invalid request - no session ID and not initialization');
        res.status(400).json({
          jsonrpc: '2.0',
          error: {
            code: -32000,
            message: 'Bad Request: No valid session ID provided',
          },
          id: null,
        });
        return;
      }

      // Handle request with existing transport
      await transport.handleRequest(req, res, req.body);
    } catch (error) {
      console.error('Error handling MCP request:', error);
      if (!res.headersSent) {
        res.status(500).json({
          jsonrpc: '2.0',
          error: {
            code: -32603,
            message: 'Internal server error',
          },
          id: null,
        });
      }
    }
  });

  // Handle GET requests for SSE streams
  app.get('/mcp', async (req, res) => {
    const sessionId = req.headers['mcp-session-id'] as string | undefined;
    if (!sessionId || !transports[sessionId]) {
      res.status(400).send('Invalid or missing session ID');
      return;
    }

    const transport = transports[sessionId];
    await transport.handleRequest(req, res);
  });

  // Handle DELETE requests for session termination
  app.delete('/mcp', async (req, res) => {
    const sessionId = req.headers['mcp-session-id'] as string | undefined;
    if (!sessionId || !transports[sessionId]) {
      res.status(400).send('Invalid or missing session ID');
      return;
    }

    const transport = transports[sessionId];
    await transport.handleRequest(req, res);
  });

  // Health check endpoint
  app.get('/health', (req, res) => {
    res.json({ status: 'ok', service: 'seller-management-mcp' });
  });

  return app;
}

// Export for standalone execution
export async function startHttpServer(port = 3001) {
  const app = createApp();
  
  return new Promise((resolve) => {
    const server = app.listen(port, () => {
      console.log(`MCP Streamable HTTP Server running on port ${port}`);
      console.log(`Health check: http://localhost:${port}/health`);
      console.log(`MCP endpoint: http://localhost:${port}/mcp`);
      resolve(server);
    });

    // Handle graceful shutdown
    process.on('SIGINT', async () => {
      console.log('Shutting down MCP server...');
      server.close(() => {
        console.log('Server shutdown complete');
        process.exit(0);
      });
    });
  });
}

// For standalone execution
if (import.meta.url === `file://${process.argv[1]}`) {
  const port = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT) : 3001;
  startHttpServer(port).catch(console.error);
}